<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/9/29
 * Time: 15:48
 */

include "config.php";

if($_SERVER["REQUEST_METHOD"] == "POST"){
    if(isset($_POST["u_id"]) && isset($_POST["p_num"]) && isset($_POST["p_id"]) && isset($_POST["p_name"]) && isset($_POST["p_price"]) && isset($_POST["P_img"])){

        $query = "SELECT*FROM `carts` WHERE u_id =? AND p_id=?";

        $stmt = $connection->prepare($query);
        $stmt->bind_param("is", $_POST["u_id"], $_POST["p_id"]);
        $stmt->execute();
        $queryResult = $stmt->get_result();
        if($queryResult->num_rows >= 1){
            //有,修改
            $p_num=$_POST["p_num"];
            $update = "UPDATE carts SET p_num=$p_num,p_total=p_price*p_num WHERE u_id=? AND p_id=? ;";
            $stmt = $connection->prepare($update);
           $stmt->bind_param("is", $_POST["u_id"], $_POST["p_id"]);
           $stmt->execute();
          if( $stmt->affected_rows>=1){
              print_r(json_encode(array("status"=>2,"msg"=>"加入成功")));
          }else{
              print_r(json_encode(array("status"=>-2,"msg"=>"加入失败")));
          }

       } else {
            //没有,添加
            $insert="INSERT INTO carts (`u_id`,`p_id`,`p_name`,`p_price`,`p_num`,`p_total`,`P_imgs`) VALUE(?,?,?,?,?,?,?);";

            $stmt = $connection->prepare($insert);
            $total=floatval($_POST["p_price"])* intval($_POST["p_num"]);
            $stmt->bind_param("iisssss", $_POST["u_id"],$_POST["p_id"],$_POST["p_name"],$_POST["p_price"],$_POST["p_num"],$total,$_POST["P_img"]);
            $stmt->execute();
            if( $stmt->affected_rows>=1){
                print_r(json_encode(array("status"=>1,"msg"=>"加入成功i")));
            }else{
                print_r(json_encode(array("status"=>-1,"msg"=>"加入成功i")));
            }
        }
        $connection->close();
    }else{
        print_r(json_encode(array("status"=>-3,"msg"=>"参数不合法")));
    }


}